<template>
  <div>
    <Card :bordered="false">
      <Row>
        <Col span="12" style="text-align: left">
          <Select clearable v-model="selectLot.id" style="width:200px;text-align: left" placeholder="停车场">
            <Option v-for="item in lotList" :value="item.id" :key="item.name">{{ item.name }}</Option>
          </Select>
          <Input v-model="txtSearch" placeholder="设备编号" style="width: 200px"/>
          <Button icon="ios-search" type="primary" @click="getParkingSpaceList(selectLot.id)"></Button>
        </Col>
      </Row>
    </Card>
    <Card :bordered="false">
      <Row>
        <Table height="500" :loading="loading" :columns="columns" :data="parkingList"></Table>
      </Row>
    </Card>
    <div class="footStatusClz">
      <div class="footStatusTxtClz">连接状态:</div>
      <div style="float: left;margin-right: 1px;margin-top: 4px;">
        <div v-if="websocketStatus!=3" style="float: left;margin-left: 3px;" class="connectClz"></div>
        <span v-if="websocketStatus!=3" class="footStatusTxtClz" style="margin-left: 2px;margin-top: -3px;">连接</span>
        <div v-if="websocketStatus==3" style="float: left;margin-left: 3px;" class="disconnectClz"></div>
        <span v-if="websocketStatus==3" class="footStatusTxtClz" style="margin-left: 2px;margin-top: -3px;">断开</span>
      </div>
    </div>
    <!--升级设备-->
    <Modal
      v-model="modal.upgrade.status"
      :title="modal.upgrade.title"
      :top="0">
      <Form :model="modal.upgrade.form" :label-width="80">
        <FormItem label="设备编号">
          <Input disabled v-model="modal.upgrade.form.deviceCode"></Input>
        </FormItem>
        <FormItem label="选择升级包">
          <Select clearable v-model="modal.upgrade.form.package" style="width:100%;text-align: left">
            <Option v-for="item in packageList" :value="item.key" :key="item.value">{{ item.value }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="modal.upgrade.status=false">取消</Button>
        <Button type="primary" :loading="waiting" @click="upgradeParkingSpace(modal.upgrade.form)">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import urlSource from '../../api/urlSource'
  import moment from 'moment'

  export default {
    name: "space",
    components: {},
    data() {
      return {
        modal : {
          status: false,
          deviceCode: '',
          upgrade: {
            status: false,
            title: "升级包安装",
            form: {
              id: '',
              deviceId: '',
              package: ''
            }
          },
        },
        lotList: [],//停车场列表
        selectLot: {
          id: "",
          name: ""
        },
        spaceStatus: [
          {
            key: 'setting',
            value: '等待升级',
          },
          {
            key: 'setSuccess',
            value: '已设置',
          },
          {
            key: 'setError',
            value: '设置失败',
          },
          {
            key: 'updated',
            value: '已升级',
          },
          {
            key: 'upgrading',
            value: '升级中',
          },
          {
            key: 'upgradeSuccess',
            value: '升级成功',
          },
          {
            key: 'upgradeError',
            value: '升级失败',
          }
        ],
        txtSearch: "",
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: '车位编号',
            key: 'code'
          },
          {
            title: '设备编号',
            key: 'deviceCode'
          },
          {
            title: '所属停车场',
            key: 'lotId',
            render: (h, params) => {
              var parkingLotName = "";
              this.lotList.forEach(v => {
                if (v.id == params.row.lotId) {
                  parkingLotName = v.name;
                }
              })
              return h('div', [
                h('div', parkingLotName)
              ]);
            }
          },
          {
            title: '当前状态',
            key: 'status',
            align: 'center',
            render: (h, params) => {
              var statusName = "";
              this.spaceStatus.forEach(v => {
                if(params.row.status=='-'){
                  statusName = params.row.status;
                }else{
                  if (v.key == params.row.status) {
                    statusName = v.value;
                  }
                }
              })
              return h('div', [
                h('div',{
                  class: (params.row.status=='upgradeSuccess')? "tagBtn tag-success" : (params.row.status=='setError' || params.row.status=='updated' || params.row.status=='upgradeError')? "tagBtn tag-danger" : "tagBtn"
                } ,statusName)
              ]);
            }
          },
          {
            title: '版本号',
            key: 'version',
            align: 'center',
          },
          {
            title: '创建时间',
            key: 'createTime',
          },
          {
            title: '操作',
            key: 'id',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px',
                  },
                  on: {
                    click: () => {
                      if(!params.row.deviceId){
                        this.$Message.warning("该设备未与电信平台关联,请先与平台关联!");
                        return;
                      }
                      // if(this.installing){
                      //   this.$Message.warning("该设备正在升级中");
                      //   return;
                      // }
                      this.modal.upgrade.status = true;
                      this.modal.upgrade.form = JSON.parse(JSON.stringify(params.row));
                    }
                  }
                }, '升级')
              ]);
            }
          }
        ],
        parkingList: [],
        deviceCodeError:'',
        packageList: [],
        loading: false,
        waiting: false,
        _version: '',
        websocketStatus: '',
        installing: false
      }
    },
    methods: {
      //获取停车场列表
      getParkingLot() {
        let url = urlSource.apiUrl + "parkingLots/" + this.$store.state.user.orgId + "/all"
        this.$http.get(url).then(res => {
          this.lotList = res.data
          this.selectLot.id = this.lotList[0].id;
          this.getParkingSpaceList(this.selectLot.id);
        }).catch(err => {
        })
      },
      //获取停车位列表
      getParkingSpaceList(lotId) {
        if(!lotId){
          this.$Message.warning('请先选择停车场');
          return ;
        }
        let url = urlSource.apiUrl + "parkingSpaces/lots/" + lotId;
        if(this.txtSearch){
          url += '?devCode=' + this.txtSearch;
        }
        this.$http.get(url).then(res => {
          if (res.data != "" && res.data != null) {
            let dataTmp = res.data;
            dataTmp.forEach(v => {
              if(v.status==7){
                v.status = 'upgradeSuccess';
              }else if(v.status==8){
                v.status = 'upgradeError';
              }else if(v.status==9){
                v.status = 'updated';
              }else{
                v.status = '-';
              }
              if(!v.version){
                v.version = '-';
              }
            });
            this.parkingList = dataTmp;
          } else {
            this.parkingList = []
          }
        }).catch(err => {

        })
      },
      getDeviceInstallPackNames(){
        this.packageList = [];
        let url = urlSource.apiUrl + "file/getInstallPackageNames";
        this.$http.get(url).then(res => {
          res.data.forEach(v => {
            let insPack = {};
            insPack.key = v;
            insPack.value = v;
            this.packageList.push(insPack);
          });
        }).catch(err => {
        })
      },
      //停车位升级
      upgradeParkingSpace(form){
        let paramObj = {};
        paramObj.deviceId = form.deviceId;
        paramObj.package = form.package;
        this._version = form.package;
        let url = urlSource.apiUrl + "deviceUpgrade/cmdNotifyStart";
        this.$http.post(url, paramObj).then(res => {
          if (res.status == 200) {
            this.modal.upgrade.status=false;
            this.$Message.success("等待升级!");
            this.parkingList.forEach(v => {
              if(v.deviceId==form.deviceId){
                v.status = 'setting';
                return;
              }
            });
            this.waiting = true;
            this.installing = true;
          }
        }).catch(err => {
          this.$Message.error("升级失败!");
        })
      },
      initWebSocket() {
        if ('WebSocket' in window) {
          this.websocket = new WebSocket(urlSource.socketUrl)
        } else {
          alert('当前浏览器 Not support websocket')
        }
        //连接错误
        this.websocket.onerror = this.setErrorMessage
        //连接成功
        this.websocket.onopen = this.setOnopenMessage
        //收到消息的回调
        this.websocket.onmessage = this.setOnmessageMessage
        //连接关闭的回调
        this.websocket.onclose = this.setOncloseMessage
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = this.onbeforeunload
      },
      setErrorMessage() {
        this.data = "WebSocket连接发生错误" + '   状态码：' + this.websocket.readyState;
      },
      setOnopenMessage() {
        this.data = "WebSocket连接成功" + '   状态码：' + this.websocket.readyState;
      },
      setOnmessageMessage(event) {
        this.data = event.data;
        this.getServerDeviceData(this.data);
      },
      //即时推送设备数据
      getServerDeviceData(pData){
        let dataObj = JSON.parse(pData);
        console.log(dataObj)
        let serviceId = dataObj.serviceId;
        //当serviceId 为 SendUpgradePackage/SetStartUpgrade/UploadUpgradeResult
        if(serviceId && (serviceId=='SendUpgradePackage'||serviceId=='SetStartUpgrade'||serviceId=='UploadUpgradeResult')){
          if(dataObj){
            this.parkingList.forEach( v=> {
              if(v.deviceId==dataObj.deviceId){
                if(!this._version){
                  this._version = this.joinAppversionStr(dataObj.appVersion);
                  console.log(this._version)
                }
                if(serviceId=='SetStartUpgrade'){
                  if(dataObj.result == 0){
                    v.status = 'setSuccess';
                  }else if(dataObj.result == 1){
                    v.status = 'setError';
                  }else{
                    v.status = 'updated';
                    this.waiting = false;
                    //升级成功后保存状态
                    let form = {'deviceId':dataObj.deviceId,'status':9,'version':this._version}
                    this.updateParkingSpaceStatus(form);
                  }
                }else if(serviceId=='SendUpgradePackage'){
                  this.waiting = true;
                  this.installing = true;
                  v.status = 'upgrading';
                }else{
                  this.waiting = false;
                  if(dataObj.result == 0){
                    v.status = 'upgradeSuccess';
                    v.version = this._version;
                    //升级成功后保存状态
                    let form = {'deviceId':dataObj.deviceId,'status':7,'version':this._version}
                    this.updateParkingSpaceStatus(form);
                  }else{
                    v.status = 'upgradeError';
                    //升级成功后保存状态
                    let form = {'deviceId':dataObj.deviceId,'status':8,'version':this._version}
                    this.updateParkingSpaceStatus(form);
                  }
                }
              }
            });
          }
        }
      },
      //字符串拼接 .
      joinAppversionStr(appVersion){
        let tmp = '';
        for(let i=0; i<appVersion.length; i++){
          tmp += appVersion[i]+'.'
        }
        return tmp+'hex';
      },
      //停车位升级成功
      updateParkingSpaceStatus(form){
        let paramObj = {};
        paramObj.deviceId = form.deviceId;
        paramObj.status = form.status;
        paramObj.version = form.version;
        let url = urlSource.apiUrl + "parkingSpaces/updateSpaceState";
        this.$http.put(url, paramObj).then(res => {
          if(res.data){
            if(paramObj.status == 1){
              this.$Message.success("升级成功!");
            }

          }
        }).catch(err => {
        })
      },
      setOncloseMessage() {
        this.data = "WebSocket连接关闭" + '   状态码：' + this.websocket.readyState;
      },
      onbeforeunload() {
        this.closeWebSocket();
      },
      //websocket发送消息
      send() {
        this.websocket.send(this.text)
        this.text = ''
      },
      closeWebSocket() {
        this.websocket.close()
      },
    },
    mounted() {
      this.$nextTick(() => {
        this.getParkingLot();
        this.getDeviceInstallPackNames();
        this.initWebSocket();
        this.ipAddr = localStorage.getItem('Ip');
      })
    },
    beforeDestroy() {
      this.onbeforeunload();
    }
  }
</script>

<style lang="less">
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .ivu-modal {
    top: 2px;
  }
  .tagBtn {
    background-color: rgba(64, 158, 255, 0.15);
    display: inline-block;
    height: 32px;
    width: 60px;
    text-align: center;
    line-height: 30px;
    font-size: 12px;
    color: #409eff;
    border-radius: 4px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(64, 158, 255, 0.2);
    white-space: nowrap;
    font-weight: bold;
  }
  .tag-success{
    background-color: rgba(103,194,58,.15);
    border-color: rgba(103,194,58,.2);
    color: #67c23a;
  }
  .tag-danger {
    background-color: hsla(0,87%,69%,.15);
    border-color: hsla(0,87%,69%,.2);
    color: #f56c6c;
  }
  .footStatusClz {
    position: fixed;
    bottom: 0px;
    left: 211px;
    background: #ddd;
    width:100%;
    height: 21px;
    padding-left: 20px;
    z-index: 999;
  }
  .connectClz {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    border: 1px solid #22de22;
    background: #22de22;
  }
  .disconnectClz {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    border: 1px solid red;
    background: red;
  }
  .footStatusTxtClz {
    color: #333;
    float: left;
    margin-right: 6px;
  }
</style>
